package com.ruoyi.message.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;


import com.ruoyi.function.domain.ChatRecord;
import com.ruoyi.function.service.IChatRecordService;
import com.ruoyi.message.notice.NoticeWebSocketHandler;
import com.ruoyi.message.notice.vo.NoticeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * -- 聊天记录Controller
 * 
 * @author ruoyi
 * @date 2025-03-24
 */
@RestController
@RequestMapping("/notice")
public class NoticeController extends BaseController
{


    @Autowired
    private IChatRecordService chatRecordService;

    /**
     * 新增-- 通知记录
     */
//    @PreAuthorize("@ss.hasPermi('notice:record:add')")
    @Log(title = "-- 通知记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody NoticeVO noticeVO)
    {
        // 接收前端数据 构造消息体 存数据库 发送消息
        noticeVO.setSenderId(1L);

        // 4. 发送消息
        try {
            ChatRecord chatRecord = new ChatRecord();
            BeanUtils.copyProperties(noticeVO,chatRecord );
            chatRecordService.insertChatRecord(chatRecord);
            NoticeWebSocketHandler.broadcastMessage(noticeVO);

        } catch (Exception e) {
            logger.info("通知发送失败{},失败原因{}",noticeVO,e);
            throw new IllegalArgumentException("通知发送失败");

        }
        return AjaxResult.success();
    }


    public void sendMessage(String receiverId, String userType, String messageContent) {
        NoticeVO noticeVO = new NoticeVO();
        noticeVO.setReceiverId(receiverId);
        noticeVO.setUserType(userType);
        noticeVO.setMessageContent(messageContent);
        add(noticeVO);
    }
}
